
import { observable, action, asMap, computed } from 'mobx';
import * as API from '../apis/signList';
import Adapter from '../adapter/index';
import * as AdapterConstant from '../constants/adapter';
import {Reply} from 'weaver-mobile-page';
import { Comment } from 'weaver-mobile-page';
import { Tools, Modal, Toast } from 'weaver-mobile';
import { toJS } from 'mobx';
import * as Api from '../apis/communicateApi';
import * as API_REQ from '../apis/form';
import remove from 'lodash/remove';
import includes from 'lodash/includes';
import * as EmSDK from '../util/emSDK';
import * as SignUtil from '../util/SignUtil';
import { Base64 } from 'js-base64';
const getLabel = Tools.getLabel;
const alert = Modal.alert;
export class SignListStore {

    @observable loglist = [];
    @observable activeKey = '1';    //初始的tab
    @observable requestLogParams = {};    //baseInfo数据
    @observable relLogParams = {};
    commonParams = {};
    @observable logParams = {};
    @observable showRefWf = false; //相关流程显示控制
    @observable refRequestid = '';
    @observable loading = false;
    @observable hasLoad = false; 
    totalCount = 0;
    @observable hasSubmitRight = false;
    @observable replyStoreMap = {}; //回复组件
    @observable signCommentStoreMap = observable.map ? observable.map({}) : asMap({});
    @observable  replyInfo = {};
    @observable signReplyVisible = null;
    @observable placeholderValue = getLabel(512567, '交流内容...');;
    @observable replyType = '';
    @observable signReplyText = '';
    @observable showReply = false;
    needInit = true; //只初始化一次
    @observable needAttachBtn = false; //是否需要回复组件底部的添加按钮
    //获取签字意见参数
    @computed get queryLogParams() {
        return {...(Number(this.activeKey) > 2 ? this.relLogParams : this.logParams)};
    }

    @computed get refReqInfo(){
        const {allrequestInfos = []} = this.requestLogParams;
        let refReq = undefined;
        if(this.refRequestid){
            allrequestInfos.map((item = {})=>{
                const {requestid = ''} = item;
                if(requestid == this.refRequestid){
                    refReq = item;
                }
            })
        }
        return refReq;
    }

    constructor(){
        this.getRequestLogBaseInfo = this.getRequestLogBaseInfo.bind(this);
        this.initLog = this.initLog.bind(this);
        this.initDatas = this.initDatas.bind(this);
        this.setState = this.setState.bind(this);
        this.updateLogParams = this.updateLogParams.bind(this);
        this.removeAllState = this.removeAllState.bind(this);
    }

    @observable communicateSettingKey = {
      isShowSignCommunicate  : '0',
      isExpendCommunicate: '0'
    }
    @action('获取基本信息')
    getRequestLogBaseInfo(params = {},reqUrlParams){
        let endParams = {...params,...this.queryLogParams};
        const rightParamKey = ['viewLogIds', 'creatorNodeId', 'isHideInput', 'isFormSignature', 'maxrequestlogid', 'wfsignlddtcnt', 'orderbytype', 'logpagesize', 'loadmethod'];
        const communicateKey = ['isShowSignCommunicate', 'isExpendCommunicate'];
        API.getRequestLogBaseInfo(endParams).then(datas => {
            const isReadPCLayout = reqUrlParams.layoutAnalysisType == "2" || this.commonParams.layoutAnalysisType == "2";
            datas['loadmethod'] = 'scroll';
            datas['wfsignlddtcnt'] = isReadPCLayout ? datas.wfsignlddtcnt : '5';
            this.requestLogParams = datas;
            let rightParams = {};
            rightParamKey.map(k => {
                rightParams[k] = datas[k];
            });
            communicateKey.map( v => {
              if(datas[v]) {
                this.communicateSettingKey[v] = datas[v];
              }
             })
            this.initDatas({isFromMobile: 1,...rightParams})
        })
    };

    @action('初始化参数')
    initLog(commonParams = {},reqUrlParams={}){
        this.commonParams = commonParams;
        const baseParamKey = ["requestid", "requestType", "workflowid", "nodeid", "signatureAttributesStr", "signatureSecretKey", "f_weaver_belongto_userid",
            "f_weaver_belongto_usertype", "authStr", "authSignatureStr", "isprint", "wfTestStr", 'isurger'];
        this.relLogParams = {
            'signatureAttributesStr': commonParams['signatureAttributesStr'],
            'signatureSecretKey': commonParams['signatureSecretKey'],
            'f_weaver_belongto_userid': commonParams['f_weaver_belongto_userid'],
            'f_weaver_belongto_usertype': commonParams['f_weaver_belongto_usertype'],
            'wfTestStr': commonParams['wfTestStr'],
            "authStr" : commonParams['authStr'],
            "authSignatureStr" : commonParams['authSignatureStr'],
            'loadmethod' : 'scroll',
            'wfsignlddtcnt': '5',
            'pgnumber': 1,
            'maxrequestlogid': 0,
        };
        const logParams = {};
        baseParamKey.map(v => {
            logParams[v] = commonParams[v];
        });
        logParams['submit'] = commonParams.requestType;
        logParams['pgnumber'] = 1;
        logParams['maxrequestlogid'] = 0;
        this.logParams = logParams;
        this.getinitParams();
        this.getRequestLogBaseInfo({},reqUrlParams);
    };

    @action getinitParams =  () => {
      Api.getInitParams(this.logParams).then(res => {
        this.hasSubmitRight = res.hasSubmitRight; 
      });
    }
    @observable communicateReplyStoreMap = observable.map ? observable.map({}) : asMap({});
    @action('初始化数据')
    initDatas(params = {},upload = false){
        Number(this.activeKey) > 2 ? this.relLogParams = {...this.relLogParams, ...params} : this.logParams = {...this.logParams, ...params};
        this.loading = true;
        API.getDatas(this.queryLogParams).then(datas => {
            const { maxrequestlogid,totalCount, loglist = [] } = datas;
            this.totalCount = totalCount;
            Number(this.activeKey) > 2 
              ? this.relLogParams = {...this.relLogParams, maxrequestlogid} 
              : this.logParams = {...this.logParams, maxrequestlogid};
            if(upload){
                this.loglist = [...this.loglist,...loglist];
            }else{
                this.loglist = [...loglist];
            }
            this.initCommentStore(this.loglist);
            this.initAtData();
            if(this.needInit) {
                this.getInitParams();
                this.needInit = false;
            }
            this.loglist.length > 0 && this.loglist.map(v => {
                let store = new Reply.Store({getAttachList: this.refReplyAttachList});
                store.doInit();
                this.communicateReplyStoreMap.set(parseInt(v.logid), store);
            })
            this.communicateReplyStore = new Reply.Store({getAttachList: this.refReplyAttachList});
            this.hasLoad = true;
        })
    };

    reqOperators = [];
     //获取At人员的数据
  initAtData = () => {
    const {requestid} = this.logParams;
    //避免多次请求
    if(this.reqOperators.length === 0 && requestid > 0) {
        API_REQ.getReqAtUser({requestid}).then((data = {}) => {
            let operators = data.operators || [];
            let reqOperatorIds = [];
            remove(operators,(item)=>{
                let isInclude = includes(reqOperatorIds,item.id);
                if(!isInclude) reqOperatorIds.push(item.id);
                return isInclude;
            });
            this.reqOperators  = operators.slice(0,100);
        })
    }
}
    @action('修改store数据')
    setState(states, cb){
        const keys = Object.keys(states);
        keys.forEach(key => {
            this[key] = states[key];
        })
        typeof cb === 'function' && cb();
    };

    @action('更新请求参数')
    updateLogParams(params = {}, isLoadLog = false){
        Number(this.activeKey) > 2 ? this.relLogParams = {...this.relLogParams, ...params} : this.logParams = {...this.logParams, ...params};
        if (isLoadLog) {
            this.initDatas(this.queryLogParams);
        }
    }

   
    
    @action('Reply添加附件')
    getInitParams = () => {
        Api.getInitParams({...this.logParams,isSubReqeuestid:this.isSubReqeuestid(),refRequestId:this.refRequestid}).then(res => {
          this.hasSubmitRight = res.hasSubmitRight;
        })
    }

    @action('刷新当前tab页的appstatus')
    refReplyAttachList = () => {
        return Api.getInitParams({...this.logParams,isSubReqeuestid:this.isSubReqeuestid(),refRequestId:this.refRequestid}).then(res => {
            if (res.attachList && res.attachList.length > 0) {
              this.setAddBtn(true);
              this.needAttachBtn = true;
            } else {
              this.setAddBtn(false);
              this.needAttachBtn = false;
            }
            return res
        })
    }

    @action('记录回复的文本')
    setReplyMark = (str = '') => {
      this.signReplyText = str;
    }

    @action('记录签字意见回复信息')
    recordReplyInfo = (data) => {
      this.replyInfo = data;
      this.signReplyVisible(true);
    }
    @observable commentReplyListMap = observable.map ? observable.map({}) : asMap({});
    @action initCommentStore = () => {
      const baseParamKey = ["requestid", "workflowid", "f_weaver_belongto_userid",
      "f_weaver_belongto_usertype", "authStr", "authSignatureStr", 'isurger'];
      let passParams = {};
      baseParamKey.map(v => {
        passParams[v] = this.logParams[v];
      });
      this.loglist.length > 0 && this.loglist.map ( v => {
        passParams = {...passParams, 
          type: 'list', 
          requestLogId: v.logid,
          'refRequestId':this.refRequestid,
          'isSubReqeuestid':this.isSubReqeuestid(),
          ...this.queryLogParams
        };
        if(v.hasCommunicationQuote) {
         this.signCommentStoreMap.set(Number(v.logid),  new Comment.Store({
            getComment: this.getContentList.bind(this, passParams),
            operate: this.getDetailOperate,
            getChild: this.getChild.bind(this),
         }));
        }
      });
      this.loading = false;       
    }

    //是否其它流程
    isSubReqeuestid = () => {
        let refRequestId = this.refRequestid;
        let allrequestInfos = this.requestLogParams.allrequestInfos || {};
        for(let index = 0; index < allrequestInfos.length; index++){
            if(allrequestInfos[index].requestid == refRequestId){
                return 1 ; //其他流程，不跳转
            }
        }
        return 0;  //当前流程，正常处理逻辑
    }

    //comment组件获取内容
    getContentList = (passParams) => {
      let map = this.commentReplyListMap;
      return Api.getContentList(passParams).then(data => {
        data.replyList.map(v => {
          map.set(parseInt(v.contentId), v.childReply); //记录所有交流的子评论数
          let str = '';
          // v.childCount = 6;
          v.childReply = v.childReply.slice(0,5);
          if(v.quoteInfo && v.quoteInfo.content) {
            str = SignUtil.getRemarkHtml(Base64.decode(v.quoteInfo.content));
            v.quoteInfo.content =  Base64.encode(str);
          } 
           if(v.childReply.length !== 0) {
              v.childReply.map(item => {
                str = SignUtil.getRemarkHtml(item.remark);
                item.content = Base64.encode(str);
              });
          } 
          str = SignUtil.getRemarkHtml(Base64.decode(v.content));
          v.content  = Base64.encode(str);
        })
        console.log(data);
        return data
      })
    }
    
    @action('获取子回复')
    getChild = (data) => {
      let replyList = [];
      let contentId = data.data.contentId;
      if(this.commentReplyListMap.has(contentId)) {
       replyList = this.commentReplyListMap.get(contentId);
      }
      // let replylist = replyList;
     return new Promise((resolve) => {
        resolve({
          replyList: toJS(replyList)
        });
      })
    }
    
   
    getDetailOperate = params => {
      const { data, parent, type: { key, type } } = params;
      this.replyComment = data;
      this.replyCommentParent = parent;
     if ( type === 'blog-comment') { // 回复      
        this.replyType = 'comment';
        this.placeholderValue = getLabel('385534', '回复')+" "+ data.creater.name;
        if ( !this.replyStoreMap[data.replyId] ) {
          this.replyStoreMap[data.replyId] = new Reply.Store({ getAttachList: this.refReplyAttachList});
          this.replyStoreMap[data.replyId].doInit();
        }
       this.signReplyVisible(true);
       EmSDK.resetBottomBtn(); //移动端隐藏底部操作按钮
      }  else if (type === 'delete') {  // 删除
        //交流的删除
        if( key === 'delContent' ) {
          this.currentModel = alert(getLabel('388758', "确认要删除吗？"), '', [
            {text: getLabel('31129', "取消")},
            {text: getLabel('33703', "确认"),
              onPress: () => {
                this.wfDiscussOperation( data, parent, 'delContent')
              }
            }
          ])
        } else if( key === 'delReply' ) {
          this.currentModel = alert(getLabel('512301', "确认要删除该评论吗？"), '', [
            {text: getLabel('31129', "取消")},
            {text: getLabel('33703', "确认"),
              onPress: () => {
                this.wfDiscussOperation( data, parent, 'delReply')
              }
            }
          ])
        }
      }  
    }
 
    @action('删除/点赞操作')
    wfDiscussOperation = (data, parent, val, callback, otherparams) => {
      let params = {
        id: data.contentId,
        operationType: val, 
        ...this.logParams
      }
      //删除
      if(val === 'delContent' || val === 'delReply') {
        params.id = data.replyId; 
        Api.doDelete(params).then( res => {
          this.relatedPage = 1;
          if( !res.canDelete) {
            Toast.info(getLabel('512478','已超过规定时间或有新内容，无法删除'), 1);
          }
          this.initDatas();
        }
      )}
    }
    @action('提交保存新交流')
    publishCommunicate = (data = {}) => { 
      let newParams = {};
      this.replyDatas = data.attach;
      let id = parseInt(this.replyInfo.logid);
      if(this.communicateReplyStoreMap.has(id)) {
        this.communicateReplyStoreMap.get(id).doClear();
      } else {
        this.communicateReplyStore.doClear(); 
      }
      let remark = data.text;
      data.imgList.map((item) => {
        remark = remark + '<img class="communicateImgPlay" src=\"' + item.imgSrc + '\">';
      })
      
        newParams = {
          "reply_man": this.replyInfo.displayname, 
          "log_useid": this.replyInfo.displayid,
          "log_displaydepid": this.replyInfo.displaydepid,
          "log_displaydepname": this.replyInfo.displaydepname,
          "log_operatedate": this.replyInfo.log_operatedate,
          "log_operatetime": this.replyInfo.log_operatetime,
          "log_nodename": this.replyInfo.log_nodename,
          "operationname": this.replyInfo.operationname,
          "sign_logid": this.replyInfo.logid,
          "signReplyText": this.signReplyText,
          "quote_type": 'quoteSign',
          'log_userType': this.replyInfo.displaytype == '0' ? '1' : this.replyInfo.displaytype == '1' ? '2' : ''
        }
      
      let params = {
        remark: remark,
        relatedprj: (toJS(this.replyDatas).task && toJS(this.replyDatas).task.map(item => item.id)) || '',
        relatedcus: (toJS(this.replyDatas).customer && toJS(this.replyDatas).customer.map(item => item.id)) || '',
        relatedwf:(toJS(this.replyDatas).workFlow && toJS(this.replyDatas).workFlow.map(item => item.id)) || '',
        relateddoc:(toJS(this.replyDatas).document && toJS(this.replyDatas).document.map(item => item.id)) || '',
        relatedacc:(toJS(this.replyDatas).uploadFile && toJS(this.replyDatas).uploadFile.map(item => item.id)) || '',
        projectIDs:(toJS(this.replyDatas).project && toJS(this.replyDatas).project.map(item => item.id)) || '',
        ...this.logParams,
        refRequestId:this.refRequestid,
        isSubReqeuestid:this.isSubReqeuestid(),
        ...newParams
      }
      Api.doSaveContent(params).then( res => {
        this.imageArr = [];
        this.initDatas();
        this.signReplyVisible(false);
        this.replyType = '';
        this.placeholderValue = getLabel('512567', '交流内容...'); 
      })
    }

    @action('提交回复评论')
    saveComment = (data, callback) => {
      this.replyDatas = data.attach;
      this.setAddBtn(this.needAttachBtn);
      let remark = data.text;
      data.imgList.map((item) => {
        remark = remark + '<img class="communicateImgPlay" src=\"' + item.imgSrc + '\">';
      })
      let params = {
        remark: remark,
        replyType: this.replyComment ? this.replyType : '',
        relatedprj: (toJS(this.replyDatas).task && toJS(this.replyDatas).task.map(item => item.id)) || '',
        relatedcus: (toJS(this.replyDatas).customer && toJS(this.replyDatas).customer.map(item => item.id)) || '',
        relatedwf:(toJS(this.replyDatas).workFlow && toJS(this.replyDatas).workFlow.map(item => item.id)) || '',
        relateddoc:(toJS(this.replyDatas).document && toJS(this.replyDatas).document.map(item => item.id)) || '',
        relatedacc:(toJS(this.replyDatas).uploadFile && toJS(this.replyDatas).uploadFile.map(item => item.id)) || '',
        projectIDs:(toJS(this.replyDatas).project && toJS(this.replyDatas).project.map(item => item.id)) || '',
        refRequestId:this.refRequestid,
        isSubReqeuestid:this.isSubReqeuestid(),
        ...this.logParams
      }
      if (this.replyComment) {
        this.replyType === 'comment' && this.replyStoreMap[this.replyComment.replyId].doClear();
      }
      if(this.replyType === 'comment') {
        if(this.replyCommentParent) {
          params = {...params, 
                    contentId: this.replyComment ? this.replyComment.contentId : 0,
                    replyId: this.replyComment.replyId, receiveUser: this.replyComment.createUser, resiveUserType: this.replyComment.createUserType }
        } else {
          params = {...params, 
                    contentId: this.replyComment ? this.replyComment.contentId : 0,
                    replyId: this.replyComment.replyId}
        }
        return Api.doSaveReply(params).then(res => {
          this.imageArr = [];
          this.signReplyVisible(false);
          if(this.signCommentStoreMap.has(this.replyComment.signLogId)) {
            this.signCommentStoreMap.get(this.replyComment.signLogId).getDatas(); //对应签字意见下的comment组件更新
          } else {
            this.initDatas();
          }
          this.replyType = '';
          this.placeholderValue = getLabel('512567', '交流内容...'); 
        })
      } 
    } 
    @observable leftConfig = [
      { type: 'blog-biaoqing' },
      { type: 'blog-tupian' },
      { type: '@' },
    ];
    setBottomButton = () => {
      if(Adapter.judgeApiSupport(AdapterConstant.API_SPEECH_TO_TEXT)) {
        this.leftConfig =[{ type: 'voice'},...this.leftConfig,{ type: 'tianjia'}];  
      } else {
        this.leftConfig =[...this.leftConfig,{ type: 'tianjia'}];  
      }
    }
    @action('回复组件设置添加按钮') 
    setAddBtn = (val) => {
      if(val) {
        if(this.leftConfig.every(v => { return v.type !== 'tianjia'})) {
          this.setBottomButton();
        }
      } else {
        this.leftConfig = [
          { type: 'blog-biaoqing' },
          { type: 'blog-tupian' },
          { type: '@' },
        ];
      }
    }
    @action('底部输入框mask点击事件')
    onMaskClick = () => {
      this.replyType = '';
      this.communicateReplyStore.doClear();
    }

    
    removeAllState(){
        this.activeKey = '1';
        this.requestLogParams = {};
        this.relLogParams = {};
        this.commonParams = {};
        this.logParams = {};
        this.showRefWf = false;
        this.refRequestid = '';
        this.loglist.replace([]);
        this.needInit = true;
        this.communicateReplyStoreMap = observable.map ? observable.map({}) : asMap({});
        this.signCommentStoreMap = observable.map ? observable.map({}) : asMap({});
        this.replyStoreMap = {};
    }

}
